//轮播图
let curNumber = 0
let timer = null
const video = document.querySelectorAll(".focus-list-video")
const ground = document.querySelector(".large-ground")
const groundImg = [
    "images/large-ground-yufengxing.jpg",
    "images/background_zhuxian.png",
    "images/background_relaguntang.jpg",
    "images/background_canlandeta.jpg",
    "images/background_banshulianren.jpg"
]
const focusPerson = document.querySelector(".focus-person")
const person_name = [
    "赵丽颖 林更新 仙侠玄幻",
    "东方仙侠 东方玄幻 武修",
    "贾玲 雷佳音 励志故事",
    "惠英红 刘浩存 祖孙情",
    "唐艺昕 谢楠 社交观察"
]
const focusContent = document.querySelector(".focus-content")
const content_detail = [
    "赵丽颖林更新甜虐仙凡恋",
    "魔教妖人，小飞棍来咯",
    "赢一次！为自己",
    "惠英红刘浩存双向救赎",
    "直通大结局！小情侣热吻拉丝",
]
const logo = document.querySelector(".logo")
const logo_url = [
    "images/video_logo-yufengxing.png",
    "",
    "images/video_logo-relaguntang.png",
    "images/video_logo-canlandeta.png",
    "images/video_logo-banshulianren.png"
]
const unChoice = document.querySelectorAll(".focus_list_unchoice")

function removeActive() {
    unChoice.forEach(item => {
        item.classList.remove('unchoice_active')
    })
}

function changeFocus(num) {
    removeActive()
    unChoice[num].classList.add('unchoice_active')
    // ground.style.background = "url(" + groundImg[num] + ") no-repeat" //复合写法会发生覆盖，图片错位
    ground.style.backgroundImage = "url(" + groundImg[num] + ")"
    logo.src = logo_url[num]
    focusPerson.innerHTML = person_name[num]
    focusContent.innerHTML = content_detail[num]
}

function autoPlay() {
    timer = setInterval(function () {
        curNumber++
        if (curNumber > video.length - 1) {
            curNumber = 0
        }
        changeFocus(curNumber)
    }, 3000)
}

video.forEach((item, num) => {
    item.addEventListener('mouseenter', function () {
        curNumber = num
        clearInterval(timer)  //此处先后顺序很重要，否则时间线错乱
        changeFocus(num)
    })
    item.addEventListener('mouseleave', function () {
        autoPlay()
    })
})
autoPlay()



//获取随机深色背景
function getRandomColor() {
    //以下的*192都是为了是获取到的颜色为深色的
    let r = Math.floor(Math.random() * 192);
    let g = Math.floor(Math.random() * 192);
    let b = Math.floor(Math.random() * 192);
    let r16 = r.toString(16).length === 1 && r.toString(16) <= "f" ? 0 + r.toString(16) : r.toString(16);
    let g16 = g.toString(16).length === 1 && g.toString(16) <= "f" ? 0 + g.toString(16) : g.toString(16);
    let b16 = b.toString(16).length === 1 && b.toString(16) <= "f" ? 0 + b.toString(16) : b.toString(16);
    let color = '#' + r16 + g16 + b16;
    return color;
}

// 新建视频节点
function addVideo() {
    const videoContent = document.querySelector(".hot-choices-content")
    const cloneVideo = videoContent.cloneNode(true)
    document.querySelector(".video-hot-choices").appendChild(cloneVideo)
}

// 滚动改变导航栏效果
function headerChange(scrollTop) {
    const header = document.querySelector(".header")
    if (parseInt(scrollTop) > 550) {
        header.style.backgroundColor = "rgb(20, 20, 20)"
        header.style.opacity = 0.96
    }
    else {
        header.style.backgroundColor = "transparent"
    }
}


let numAll = 0
let pageAll = 1
let storageListAll = []
let getStorageListAll
function changeContent_all() {
    // 根据获取的数据修改新建节点的参数
    const name = document.querySelectorAll(".video-hot-choices_all .choices-name")
    const title = document.querySelectorAll(".video-hot-choices_all .choices_hover_title")
    const intro = document.querySelectorAll(".video-hot-choices_all .choices-introduction")
    const hoverIntro = document.querySelectorAll(".video-hot-choices_all .choices_hover_content1")
    const cover = document.querySelectorAll(".video-hot-choices_all .choice-content img")
    const status = document.querySelectorAll(".video-hot-choices_all .choices-bottom-status")
    const choiceHover = document.querySelectorAll(".video-hot-choices_all .choices_hover")
    //获取十条视频数据
    const xhr = new XMLHttpRequest()
    let data
    xhr.responseType = 'json'
    xhr.open('GET', `https://blog.zifeiyu.love/video/search?type=&name&page=${pageAll}&size=10`)
    xhr.send()
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                //查看返回数据情况
                // console.log(xhr.response)
                data = xhr.response.data.records
                storageListAll = storageListAll.concat(data)
                // console.log(data[1])
            }
        }
    }
    xhr.addEventListener('loadend', () => {
        console.log(data)
        for (let i = 0; i <= 9; i++) {
            name[numAll].innerHTML = data[i].name
            title[numAll].innerHTML = data[i].name
            intro[numAll].innerHTML = data[i].brief
            hoverIntro[numAll].innerHTML = data[i].brief
            cover[numAll].src = data[i].cover
            choiceHover[numAll].style.background = getRandomColor();
            if (data[i].type === "电视剧") {
                if (data[i].nowCount < 10)
                    status[numAll].innerHTML = `更新至0${data[i].nowCount}集`
                else status[numAll].innerHTML = `更新至${data[i].nowCount}集`
            }
            else if (data[i].type === "电影")
                status[numAll].innerHTML = `${Number(data[i].mark).toFixed(1)}分`
            numAll++
        }
    })
}

//触底加载
window.onload = function () {
    //先加载十个视频
    document.querySelector(".hot-head-right span").classList.add('hot-head-right_span_active')
    for (let i = 1; i < 10; i++) {
        addVideo()
    }
    changeContent_all()
    pageAll++   //换页数据加载
    window.onscroll = function () {
        let scrollTop = document.documentElement.scrollTop
        let clientHeight = document.documentElement.clientHeight
        let bodyHeight = document.body.clientHeight
        //下拉导航栏变化
        headerChange(scrollTop)
        //触底新加载10个视频
        if (parseInt(bodyHeight - scrollTop - clientHeight) < 350) {
            //复制10个节点
            for (let i = 1; i <= 10; i++) {
                addVideo()
            }
            changeContent_all()
            pageAll++
            if (pageAll === 4) pageAll = 1
            //存储视频信息到本地，便于后续使用id
            console.log(storageListAll)
            localStorage.setItem('storageDataAll', JSON.stringify(storageListAll))
            getStorageListAll = JSON.parse(localStorage.getItem('storageDataAll'))
        }
    }
    // changeRandom()
    collectItem()
    toDetail()
}


// 获取视频数据数组
// 1.复制节点 => 插入页面 => 获取所有相同标签 => 循环数组修改标签的内容
// 2.复制节点 => children方式修改内容 => 插入页面


//热播栏分类改变item
let num = 0
let storageList = []
let getStorageList
function changeContent(type) {
    // 根据获取的数据修改新建节点的参数
    let name, title, intro, hoverIntro, cover, status, choiceHover, typeName
    if (type === 1) {
        typeName = '电视剧'
        name = document.querySelectorAll(".video-hot-choices_TVplay .choices-name")
        title = document.querySelectorAll(".video-hot-choices_TVplay .choices_hover_title")
        intro = document.querySelectorAll(".video-hot-choices_TVplay .choices-introduction")
        hoverIntro = document.querySelectorAll(".video-hot-choices_TVplay .choices_hover_content1")
        //const hoverIntro = document.querySelectorAll(".choices_hover_content2")
        cover = document.querySelectorAll(".video-hot-choices_TVplay .choice-content img")
        status = document.querySelectorAll(".video-hot-choices_TVplay .choices-bottom-status")
        choiceHover = document.querySelectorAll(".video-hot-choices_TVplay .choices_hover")
    }
    else if (type === 3) {
        typeName = '电影'
        name = document.querySelectorAll(".video-hot-choices_movie .choices-name")
        title = document.querySelectorAll(".video-hot-choices_movie .choices_hover_title")
        intro = document.querySelectorAll(".video-hot-choices_movie .choices-introduction")
        hoverIntro = document.querySelectorAll(".video-hot-choices_movie .choices_hover_content1")
        // cosnt hoverIntro = document.querySelectorAll(".choices_hover_content2")
        cover = document.querySelectorAll(".video-hot-choices_movie .choice-content img")
        status = document.querySelectorAll(".video-hot-choices_movie .choices-bottom-status")
        choiceHover = document.querySelectorAll(".video-hot-choices_movie .choices_hover")
    }
    //获取十条视频数据
    const xhr = new XMLHttpRequest()
    let data
    xhr.responseType = 'json'
    xhr.open('GET', `https://blog.zifeiyu.love/video/search?type=${typeName}&name&page=1&size=20`)
    xhr.send()
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                //查看返回数据情况
                // console.log(xhr.response.data.records)
                data = xhr.response.data.records
                // console.log(data)
                storageList = storageList.concat(data)
                // console.log(data[1])
            }
        }
    }
    //数据更新
    xhr.addEventListener('loadend', () => {
        console.log(data)
        for (let i = 0; i < 15; i++) {
            name[num].innerHTML = data[i].name
            title[num].innerHTML = data[i].name
            intro[num].innerHTML = data[i].brief
            hoverIntro[num].innerHTML = data[i].brief
            cover[num].src = data[i].cover
            choiceHover[num].style.background = getRandomColor();
            if (data[i].type === "电视剧") {
                if (data[i].nowCount < 10)
                    status[num].innerHTML = `更新至0${data[i].nowCount}集`
                else status[num].innerHTML = `更新至${data[i].nowCount}集`
            }
            else if (data[i].type === "电影")
                status[num].innerHTML = `${Number(data[i].mark).toFixed(1)}分`
            num++
        }
    })
}

// 热播tab栏切换
const videoType = document.querySelectorAll(".hot-head-right span")
const videoTypeContent = document.querySelectorAll(".video-hot-choices")
videoType.forEach((item, type) => {
    item.addEventListener("click", function () {
        // 改变导航栏效果
        videoType.forEach(itemType => {
            itemType.classList.remove('hot-head-right_span_active')
        })
        item.classList.add('hot-head-right_span_active')
        const cloneVideo = document.querySelector(".hot-choices-content").cloneNode(true)
        videoTypeContent.forEach(item => {
            item.style.display = "none"
        })
        videoTypeContent[type].style.display = "flex"
        videoTypeContent[type].appendChild(cloneVideo)
        for (let i = 1; i < 15; i++) {
            const cloneVideo2 = cloneVideo.cloneNode(true)
            videoTypeContent[type].appendChild(cloneVideo2)
        }
        num = 0
        changeContent(type)
        //无限下拉加载
        window.onscroll = function () {
            let scrollTop = document.documentElement.scrollTop
            let clientHeight = document.documentElement.clientHeight
            let bodyHeight = document.body.clientHeight
            //下拉导航栏变化
            headerChange(scrollTop)
            //触底新加载10个视频
            if (parseInt(bodyHeight - scrollTop - clientHeight) < 350) {
                //复制10个节点
                for (let i = 1; i <= 15; i++) {
                    const cloneVideo2 = cloneVideo.cloneNode(true)
                    videoTypeContent[type].appendChild(cloneVideo2)
                }
                changeContent(type)
            }
        }
    })
    collectItem()
    toDetail()
})


// 换一换
let changeNum = 0
function changeRandom10Item() {
    // 根据获取的数据修改新建节点的参数
    const name = document.querySelectorAll(".video-hot-choices_all .choices-name")
    const title = document.querySelectorAll(".video-hot-choices_all .choices_hover_title")
    const intro = document.querySelectorAll(".video-hot-choices_all .choices-introduction")
    const hoverIntro = document.querySelectorAll(".video-hot-choices_all .choices_hover_content1")
    // const hoverIntro = document.querySelectorAll(".choices_hover_content2")
    const cover = document.querySelectorAll(".video-hot-choices_all .choice-content img")
    const status = document.querySelectorAll(".video-hot-choices_all .choices-bottom-status")
    const choiceHover = document.querySelectorAll(".video-hot-choices_all .choices_hover")

    //获取十条视频数据
    const xhr = new XMLHttpRequest()
    let data
    xhr.responseType = 'json'
    xhr.open('GET', `https://blog.zifeiyu.love/video/random?size=10`)
    xhr.send()
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                data = xhr.response.data
                // console.log(data)
                storageListAll = storageListAll.concat(data)
            }
        }
    }
    xhr.addEventListener('loadend', () => {
        console.log(data)
        // let number = changeNum
        for (let i = 0; i <= 9; i++, changeNum++) {
            name[changeNum].innerHTML = data[i].name
            title[changeNum].innerHTML = data[i].name
            intro[changeNum].innerHTML = data[i].brief
            hoverIntro[changeNum].innerHTML = data[i].brief
            cover[changeNum].src = data[i].cover
            choiceHover[changeNum].style.background = getRandomColor();
            if (data[i].type === "电视剧") {
                if (data[i].nowCount < 10)
                    status[changeNum].innerHTML = `更新至0${data[i].nowCount}集`
                else status[changeNum].innerHTML = `更新至${data[i].nowCount}集`
            }
            else if (data[i].type === "电影") {
                status[changeNum].innerHTML = `${Number(data[i].mark).toFixed(1)}分`
            }
        }
        if (changeNum < numAll) {
            console.log(changeNum)
            changeRandom10Item()
        }
    })
}


document.querySelector(".hot-head-change").addEventListener('click', function () {
    changeNum = 0
    storageListAll = []
    changeRandom10Item()
})

// 跳转页面
function toDetail() {
    const collect = document.querySelectorAll(".choices_hover_collect")
    for (let i = 0; i < collect.length; i++) {
        collect[i].addEventListener("click", function () {
            return
        })
    }
    const videoDetail = document.querySelectorAll(".hot-choices-content")
    videoDetail.forEach((item, number) => {
        item.addEventListener("click", function () {
            let playNum = getStorageListAll[number].id
            let playType = getStorageListAll[number].type
            localStorage.setItem('playId', playNum)
            localStorage.setItem('playType', playType)
            window.open("detailpage.html", "_blank")
        })
    })
}

// 搜索
const searchInput = document.querySelector(".search-input")
const searchDroplist = document.querySelector(".search_droplist")
function getSearch(inputValue) {
    const xhr = new XMLHttpRequest()
    xhr.open('GET', `https://blog.zifeiyu.love/video/search?type&name=${encodeURIComponent(inputValue)}&page=1&size=32`, true)
    xhr.send()
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const searchData = JSON.parse(xhr.responseText)
                const searchResult = searchData.data.records
                // 动态生成下拉列表
                const result = searchResult.map(data => {
                    return `
                    <div class="search_item" data-id="${data.id}">
                        ${data.name} - ${data.brief} (${data.type})
                    </div> `
                }).join('')
                searchDroplist.innerHTML = result
                // 点击词条跳转
                const searchItems = document.querySelectorAll('.search_item')
                searchItems.forEach(item => {
                    item.addEventListener('click', function () {
                        let playNum = item.dataset.id
                        let playType = item.dataset.type
                        localStorage.setItem('playId', playNum)
                        localStorage.setItem('playType', playType)
                        window.open("detailpage.html", "_blank")
                    })
                })
            } else {
                console.error('Request failed:' + xhr.status)
            }
        }
    }
}

// 搜索热门词条
function getHot() {
    const xhr = new XMLHttpRequest()
    xhr.responseType = 'json'
    xhr.open('GET', `https://blog.zifeiyu.love/video/search?type&name=&page=1&size=10`, true)
    xhr.send()
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const searchResult = xhr.response.data.records
                // 动态生成下拉列表
                const result = searchResult.map(searchData => {
                    return `
                    <div class="search_item" data-id="${searchData.id}">
                        ${searchData.name} - ${searchData.brief} (${searchData.type})
                    </div> `
                }).join('')
                const searchHead = `
                <div class="search_droplist_hot_head">热门搜索</div>
                `
                searchDroplist.innerHTML = searchHead + result
                // 点击词条跳转
                const searchItems = document.querySelectorAll('.search_item')
                searchItems.forEach(item => {
                    item.addEventListener('click', function () {
                        let playNum = item.dataset.id
                        let playType = item.dataset.type
                        localStorage.setItem('playId', playNum)
                        localStorage.setItem('playType', playType)
                        window.open("detailpage.html", "_blank")
                    })
                })
            } else {
                console.error('Request failed:' + xhr.status)
            }
        }
    }
}

// 搜索事件
searchInput.addEventListener('click', function (event) {
    const inputValue = event.target.value
    if (inputValue.length === 0) {
        getHot()
    }
    searchDroplist.style.display = "block"
})
searchInput.addEventListener('input', function (event) {
    const inputValue = event.target.value
    searchDroplist.style.display = "block"
    if (inputValue.length > 0) {
        getSearch(inputValue)
    } else {
        getHot()
    }

    console.log(inputValue.length)
})
document.querySelector(".search").addEventListener('mouseleave', function () {
    searchDroplist.style.display = "none"
})


let token = localStorage.getItem("token")
// 收藏
function collectItem() {
    const collect = document.querySelectorAll(".choices_hover_collect")
    const collect1 = document.querySelectorAll(".collect_before")
    const collect2 = document.querySelectorAll(".choices_collect-active")
    collect.forEach(function (item, num) {
        console.log(item)
        item.addEventListener("click", function (e) {
            if (token) {
                collect1[num].style.display = "none"
                collect2[num].style.display = "block"
                const xhr = new XMLHttpRequest()
                xhr.responseType = 'json'
                xhr.open('GET', `https://blog.zifeiyu.love/video/star?id=${getStorageListAll[num].id}`)
                xhr.setRequestHeader("token", `${token}`)
                xhr.send()
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            console.log(xhr.response.data)
                            alert(1)
                        } else {
                            console.error('Request failed:' + xhr.status)
                        }
                    }
                }
            }
            else {
                alert('未登录')
            }
            console.log(num)
            e.stopPropagation()
        })
    })
}





















